package com.zidongxiangxi.rabbit.producer.transaction;

import com.zidongxiangxi.rabbit.producer.transaction.listener.TransactionListener;
import org.springframework.transaction.support.TransactionSynchronization;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * RabbitMQ事务同步器
 *
 * @author chenxudong
 * @date 2020/11/07
 */
public class RabbitTransactionSynchronization implements TransactionSynchronization {
	private final List<TransactionListener> listeners;

	public RabbitTransactionSynchronization(List<TransactionListener> listeners) {
		if (Objects.isNull(listeners)) {
			this.listeners = new LinkedList<>();
		} else {
			this.listeners = listeners;
		}
	}

	@Override
	public void suspend() {
		for (TransactionListener listener : listeners) {
			listener.suspend();
		}
	}

	@Override
	public void resume() {
		for (TransactionListener listener : listeners) {
			listener.resume();
		}
	}

	@Override
	public void flush() {

	}

	@Override
	public void beforeCommit(boolean readOnly) {
		if (readOnly) {
			return;
		}
		for (TransactionListener listener : listeners) {
			listener.beforeCommit();
		}
	}

	@Override
	public void beforeCompletion() {
		for (TransactionListener listener : listeners) {
			listener.beforeCompletion();
		}
	}

	@Override
	public void afterCommit() {
		for (TransactionListener listener : listeners) {
			listener.afterCommit();
		}
	}

	@Override
	public void afterCompletion(int status) {
		for (TransactionListener listener : listeners) {
			listener.afterCompletion();
		}
	}
}
